<template>
  <div class="request-definition-detail">
    <header class="mb-8">
      <div class="flex items-center">
        <router-link to="/request/definitions" class="mr-4 text-light-dark hover:text-primary">
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
          </svg>
        </router-link>
        <h1 class="glow-text">请求定义详情</h1>
      </div>
      <div class="tech-line mt-2"></div>
    </header>

    <div v-if="loading" class="flex justify-center items-center py-12">
      <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
    </div>

    <div v-else-if="!definition" class="text-center py-12 text-light-dark">
      未找到请求定义或加载失败
    </div>

    <div v-else>
      <!-- 请求基本信息 -->
      <div class="card mb-8">
        <h2 class="text-xl font-medium mb-6">基本信息</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">请求 ID</div>
              <div class="font-mono">{{ definition._id }}</div>
            </div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">请求名称</div>
              <div>{{ definition.name }}</div>
            </div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">请求方法</div>
              <span :class="{
                'badge badge-blue': definition.method === 'GET',
                'badge badge-green': definition.method === 'POST',
                'badge badge-purple': definition.method === 'PUT',
                'badge badge-orange': definition.method === 'DELETE',
                'badge badge-yellow': !['GET', 'POST', 'PUT', 'DELETE'].includes(definition.method)
              }">{{ definition.method }}</span>
            </div>
          </div>
          
          <div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">请求 URL</div>
              <div class="font-mono">{{ definition.url }}</div>
            </div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">创建时间</div>
              <div>{{ formatTime(definition.created_at) }}</div>
            </div>
            <div class="mb-4">
              <div class="text-light-dark mb-1">更新时间</div>
              <div>{{ formatTime(definition.updated_at) }}</div>
            </div>
          </div>
          
          <div class="md:col-span-2">
            <div class="text-light-dark mb-1">描述</div>
            <div>{{ definition.description || '无描述' }}</div>
          </div>
        </div>
      </div>

      <!-- 请求详情 -->
      <div class="card mb-8">
        <h2 class="text-xl font-medium mb-6">请求详情</h2>
        
        <div class="mb-6">
          <div class="text-light-dark mb-2">请求头</div>
          <div class="bg-dark-darker p-4 rounded-lg font-mono text-sm overflow-x-auto">
            <pre>{{ formatHeaders(definition.headers) }}</pre>
          </div>
        </div>

        <div v-if="definition.body">
          <div class="text-light-dark mb-2">请求体</div>
          <div class="bg-dark-darker p-4 rounded-lg font-mono text-sm overflow-x-auto">
            <pre>{{ formatBody(definition.body, definition.headers) }}</pre>
          </div>
        </div>
      </div>

      <!-- 执行历史 -->
      <div class="card mb-8">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-xl font-medium">执行历史</h2>
          <router-link :to="`/request/definitions/${definition._id}/execute`" class="btn btn-primary">
            <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path>
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            执行请求
          </router-link>
        </div>

        <div v-if="loadingHistory" class="flex justify-center items-center py-12">
          <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
        </div>

        <div v-else-if="executionHistory.length === 0" class="text-center py-12 text-light-dark">
          暂无执行历史
        </div>

        <div v-else class="overflow-x-auto">
          <table class="w-full">
            <thead>
              <tr class="border-b border-dark-light">
                <th class="py-3 px-4 text-left">执行时间</th>
                <th class="py-3 px-4 text-left">状态码</th>
                <th class="py-3 px-4 text-left">响应时间</th>
                <th class="py-3 px-4 text-left">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="execution in executionHistory"
                :key="execution.id"
                class="border-b border-dark-light hover:bg-dark-darker"
              >
                <td class="py-3 px-4 text-light-dark">{{ formatTime(execution.executed_at) }}</td>
                <td class="py-3 px-4">
                  <span :class="{
                    'text-accent-blue': execution.status_code < 300,
                    'text-accent-yellow': execution.status_code >= 300 && execution.status_code < 400,
                    'text-accent-orange': execution.status_code >= 400 && execution.status_code < 500,
                    'text-accent-pink': execution.status_code >= 500
                  }">{{ execution.status_code }}</span>
                </td>
                <td class="py-3 px-4">{{ execution.response_time.toFixed(2) }} ms</td>
                <td class="py-3 px-4">
                  <button
                    @click="showExecutionResult(execution)"
                    class="text-primary hover:text-primary-light mr-2"
                    title="查看结果"
                  >
                    <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                    </svg>
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="flex justify-between">
        <router-link to="/request/definitions" class="btn btn-outline">
          返回列表
        </router-link>
        <div class="flex space-x-2">
          <router-link :to="`/request/definitions/${definition._id}/execute`" class="btn btn-primary">
            <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path>
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            执行请求
          </router-link>
          <button @click="deleteDefinition" class="btn btn-danger">
            <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
            </svg>
            删除请求
          </button>
        </div>
      </div>
    </div>

    <!-- 执行结果弹窗 -->
    <div v-if="showResultModal" class="fixed inset-0 bg-dark-darker bg-opacity-75 flex items-center justify-center z-50">
      <div class="bg-dark-light rounded-lg w-full max-w-4xl cyber-border">
        <div class="p-6">
          <div class="flex justify-between items-start mb-6">
            <h2 class="text-2xl font-bold">执行结果</h2>
            <button @click="showResultModal = false" class="text-light-dark hover:text-primary">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>

          <div class="mb-4">
            <div class="text-light-dark mb-2">状态码</div>
            <div :class="{
              'text-accent-blue': selectedExecution.status_code < 300,
              'text-accent-yellow': selectedExecution.status_code >= 300 && selectedExecution.status_code < 400,
              'text-accent-orange': selectedExecution.status_code >= 400 && selectedExecution.status_code < 500,
              'text-accent-pink': selectedExecution.status_code >= 500
            }">{{ selectedExecution.status_code }}</div>
          </div>

          <div class="mb-4">
            <div class="text-light-dark mb-2">响应时间</div>
            <div>{{ selectedExecution.response_time.toFixed(2) }} ms</div>
          </div>

          <div class="mb-4">
            <div class="text-light-dark mb-2">响应头</div>
            <div class="bg-dark-darker p-4 rounded-lg font-mono text-sm overflow-x-auto max-h-40 overflow-y-auto">
              <pre>{{ formatHeaders(selectedExecution.headers) }}</pre>
            </div>
          </div>

          <div class="mb-6">
            <div class="text-light-dark mb-2">响应体</div>
            <div class="bg-dark-darker p-4 rounded-lg font-mono text-sm overflow-x-auto max-h-80 overflow-y-auto">
              <pre>{{ formatBody(selectedExecution.body) }}</pre>
            </div>
          </div>

          <div class="flex justify-end">
            <button @click="showResultModal = false" class="btn btn-outline">关闭</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { requestApi } from '../../api';

// 路由
const route = useRoute();
const router = useRouter();
const definitionId = route.params.id as string;

// 状态变量
const loading = ref(false);
const loadingHistory = ref(false);
const definition = ref<any>(null);
const executionHistory = ref<any[]>([]);
const showResultModal = ref(false);
const selectedExecution = ref<any>({
  status_code: 0,
  response_time: 0,
  headers: {},
  body: ''
});

// 获取请求定义详情
const fetchDefinitionDetail = async () => {
  try {
    loading.value = true;
    const response = await requestApi.getDefinitionById(definitionId);
    
    if (response && typeof response === 'object') {
      definition.value = response;
    } else {
      // 模拟数据
      definition.value = {
        _id: definitionId,
        name: '获取用户信息',
        method: 'GET',
        url: 'https://api.example.com/users/123',
        description: '获取指定ID的用户详细信息',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer token123'
        },
        body: null,
        created_at: new Date(Date.now() - 86400000).toISOString(),
        updated_at: new Date(Date.now() - 86400000).toISOString()
      };
    }
  } catch (error) {
    console.error('获取请求定义详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 获取执行历史
const fetchExecutionHistory = async () => {
  try {
    loadingHistory.value = true;
    
    // 这里应该有一个获取执行历史的API，暂时使用模拟数据
    executionHistory.value = [
      {
        id: '1',
        definition_id: definitionId,
        status_code: 200,
        response_time: 45.2,
        headers: {
          'Content-Type': 'application/json',
          'Cache-Control': 'no-cache',
          'X-Request-ID': '12345'
        },
        body: JSON.stringify({
          id: 123,
          name: 'John Doe',
          email: 'john@example.com',
          created_at: '2023-01-01T00:00:00Z'
        }),
        executed_at: new Date(Date.now() - 120000).toISOString()
      },
      {
        id: '2',
        definition_id: definitionId,
        status_code: 404,
        response_time: 32.1,
        headers: {
          'Content-Type': 'application/json',
          'Cache-Control': 'no-cache',
          'X-Request-ID': '12346'
        },
        body: JSON.stringify({
          error: 'User not found',
          code: 'NOT_FOUND'
        }),
        executed_at: new Date(Date.now() - 180000).toISOString()
      },
      {
        id: '3',
        definition_id: definitionId,
        status_code: 500,
        response_time: 156.3,
        headers: {
          'Content-Type': 'application/json',
          'Cache-Control': 'no-cache',
          'X-Request-ID': '12347'
        },
        body: JSON.stringify({
          error: 'Internal server error',
          code: 'SERVER_ERROR'
        }),
        executed_at: new Date(Date.now() - 240000).toISOString()
      }
    ];
  } catch (error) {
    console.error('获取执行历史失败:', error);
  } finally {
    loadingHistory.value = false;
  }
};

// 格式化请求头
const formatHeaders = (headers: any) => {
  if (!headers) return 'No headers';
  
  return Object.entries(headers)
    .map(([key, value]) => `${key}: ${value}`)
    .join('\n');
};

// 格式化请求/响应体
const formatBody = (body: any, headers?: any) => {
  if (!body) return 'No body';
  
  // 检查内容类型
  const contentType = headers && headers['Content-Type'] ? headers['Content-Type'] : '';
  
  // 如果是 JSON
  if (contentType.includes('application/json') || typeof body === 'object') {
    try {
      // 如果已经是字符串，尝试解析它
      if (typeof body === 'string') {
        const parsed = JSON.parse(body);
        return JSON.stringify(parsed, null, 2);
      }
      // 如果已经是对象，直接格式化
      return JSON.stringify(body, null, 2);
    } catch (e) {
      // 如果解析失败，返回原始内容
      return body;
    }
  }
  
  // 其他类型直接返回
  return body;
};

// 格式化时间
const formatTime = (timestamp: string) => {
  if (!timestamp) return '未知';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN');
};

// 显示执行结果
const showExecutionResult = (execution: any) => {
  selectedExecution.value = execution;
  showResultModal.value = true;
};

// 删除请求定义
const deleteDefinition = async () => {
  if (!confirm('确定要删除该请求定义吗？此操作不可恢复。')) return;

  try {
    await requestApi.deleteDefinition(definitionId);
    router.push('/request/definitions');
  } catch (error: any) {
    console.error('删除请求定义失败:', error);
    alert(`删除请求定义失败: ${error.response?.data?.error || error.message}`);
  }
};

// 生命周期钩子
onMounted(async () => {
  await Promise.all([
    fetchDefinitionDetail(),
    fetchExecutionHistory()
  ]);
});
</script>

<style scoped>
/* 可以添加组件特定的样式 */
</style>
